package com.neusoft.elm_servlet.framework;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 自定义前端控制器 拦截url格式要求： /控制器类名/控制器方法名
 */

@WebServlet("/")
public class DispatcherServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 734173877017965836L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		PrintWriter out = resp.getWriter();
		ObjectMapper om = new ObjectMapper();
		
		String url = req.getServletPath();
		
		String[] arr = url.split("/");
		if (arr.length==0) {
			out.print("路径不正确！");
			return;
		}
		String className = arr[1];
		String methodName = arr[2];
		
		//反射机制，在程序运行过程中，动态的获取类中数据的方式
		//1.加载类，获取类对象clazz
		try {
			//通过Controller类全名获取此类的所有信息
			Class<?> clazz = Class.forName("com.neusoft.elm_servlet.controller."+className);
			//2.创建对象
			Object newInstance = clazz.newInstance();
			//获取方法的方法对象。。。
			Method method = clazz.getMethod(methodName, new Class[]{HttpServletRequest.class,HttpServletResponse.class});
			//执行方法
			Object result = method.invoke(newInstance, new Object[]{req,resp});
			
			out.print(om.writeValueAsString(result));
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}
